<?php
/**
 * UserController
 *
 * PHP Version 5.4
 *
 * @author liuxuTJ <liuxuphp@icesmart.cn>
 */
namespace Admin\Controller;
use Admin\Service\BaseService;
use Admin\Service\PermissionService;
use Admin\Service\UserService;
use Model\UserGroupModel;
use Think\Controller;
use Model\UserModel;

/**
 * Class UserController
 */
class UserController extends BaseController {

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->display();
    }
    /**
     * 用户登录
     */
    public function login(){
        $username = trim(I('post.username'));
        $password = trim(I('post.password'));

        if(empty($username)){
            $this->error('用户名不可为空');
        }
        if(empty($password)){
            $this->error('密码不可为空');
        }

        $userService = new UserService();
        $userResult = $userService->validate($username, md5($password));
        if(empty($userResult)){
            $this->error('用户名或密码错误');
        }

        $userModel = new UserModel();
        $userInfo = $userModel->get($userResult);
        if($userInfo['permission'] != 2){
            $this->error('对不起，您没有权限登陆');
        }
        if($userInfo['status'] == 0){
            $this->error('此帐号已被禁用，请您联系管理员');
        }

        $data = [];
        $data['lastTime'] = date('Y-m-d H:i:s');
        $data['lastIp'] = get_client_ip();
        $userModel->where('id = '.$userInfo['id'])->save($data);
        cookie('userId',$userInfo['id']);

        $this->success('登录成功',__ROOT__.'/Admin/',1);
    }

    /**
     * 用户登出
     */
    public function logout(){
        cookie('userId',null);
        $this->success('您已安全退出',__ROOT__.'/Admin/User/index.html',1);
    }

    /**
     * 用户列表
     */
    public function userList()
    {
        $userService = new UserService();
        $userInfo = $userService->validateLogin();   //验证是否登录
        $permissionService = new PermissionService();
        $permission = $permissionService->validate($userInfo['userId'], [
            'add' => '/'.CONTROLLER_NAME.'/add',
            'permission' => '/'.CONTROLLER_NAME.'/permission',
            'edit' => '/'.CONTROLLER_NAME.'/edit',
            'fordCash' => '/Gift/fordCash',
        ]);


        $userModel = new UserModel();
        $page = $this->page($userModel, null);
        $show = $page->show();
        $userList = $userModel->order('createTime DESC')->limit($page->firstRow.','.$page->listRows)->select();
        $userGroupModel = new UserGroupModel();
        foreach($userList as $k=>$v){
            $userList[$k]['groupInfo'] = $userGroupModel->get($v['groupId']);
        }

        $userGroupList = $userGroupModel->where('status = 1')->order('createTime DESC')->select();

        $menu = $permissionService->menu($userInfo['userId']);

        $this->assign('menu', $menu);
        $this->assign('url', '/User/userList');
        $this->assign('permission', $permission);
        $this->assign('userList',$userList);
        $this->assign('userGroupList',$userGroupList);
        $this->assign('page',$show);
        $this->assign('userInfo',$userInfo);
        $this->display();
    }

    /**
     * 添加用户
     */
    public function add()
    {
        $userName = trim(I('post.username'));
        $permission = I('post.permission');
        $userGroup = I('post.userGroup');
        $createTime = date('Y-m-d H:i:s');

        if(empty($userName)){
            $this->error('用户名不允许为空');
        }

        $userModel = new UserModel();
        $userAdd = $userModel->add([
            'username'  => $userName,
            'password' => md5(123),
            'permission' => $permission,
            'groupId' => $userGroup,
            'createTime'    => $createTime
        ]);

        if(!$userAdd){
            $this->error('添加失败');
        }else{
            $this->success('添加成功');
        }
    }

    /**
     * 修改用户
     */
    public function edit()
    {
        $userService = new UserService();
        $userInfo = $userService->validateLogin();

        $userId = I('get.id');
        if(empty($userId)){
            $this->error('参数异常');
        }
        $userModel = new UserModel();
        $user = $userModel->get($userId);

        $permissionService = new PermissionService();
        $menu = $permissionService->menu($userInfo['userId']);

        $this->assign('menu', $menu);
        $this->assign('url', '/User/userList');
        $this->assign('user', $user);
        $this->display();
    }

    /**
     * 保存用户
     */

    public function save()
    {
        $userId = I('post.id');
        $picture = $_FILES['picture'];
        $nickname = I('post.nickname');
        $permission = I('post.permission');
        $status = I('post.status');
        $password = I('post.password');
        $data = [];


        if(!empty($picture['name'])){
            $baseService = new BaseService();
            $data['picture'] = $baseService->upload($picture);
        }
        if(!empty($password)){
            $data['password'] = md5($password);
        }
        $data['nickname'] = $nickname;
        $data['permission'] = $permission;
        $data['status'] = $status;

        $userModel = new UserModel();
        $userEdit = $userModel->update($data, $userId);
        if($userEdit){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }


    /**
     * 修改密码
     */
    public function password()
    {
        $userService = new UserService();
        $userInfo = $userService->validateLogin();

        $permissionService = new PermissionService();
        $menu = $permissionService->menu($userInfo['userId']);

        $this->assign('url', '/User/password');
        $this->assign('menu', $menu);
        $this->assign('userInfo', $userInfo);
        $this->display();
    }

    /**
     * 保存密码
     */
    public function modifyPassword()
    {
        $password = I('post.password');
        $newPassword = I('post.newPassword');
        $confirmPassword = I('post.confirmPassword');
        $userName = I('post.userName');

        if(empty($password) or empty($newPassword) or empty($confirmPassword)){
            $this->error('密码不允许为空');
        }

        $userService = new UserService();
        $userResult = $userService->validate($userName, md5($password));

        if(empty($userResult)){
            $this->error('当前密码不正确');
        }
        if($password == $newPassword){
            $this->error('当前密码不能与原始密码一样');
        }
        if($newPassword != $confirmPassword){
            $this->error('两次密码输入不一致');
        }

        $userModel = new UserModel();
        $passwordUpdate = $userModel->where('username = "'.$userName.'"')->setField('password',md5($newPassword));
        if(!$passwordUpdate){
            $this->error('修改失败');
        }else{
            cookie('userId',null);
            $this->success('修改成功',__ROOT__.'/Admin/User/index.html',1);
        }
    }


    /**
     * 分配权限
     */
    public function permission()
    {
        $userService = new UserService();
        $user = $userService->validateLogin();   //验证是否登录

        $userId = I('get.id');
        if(empty($userId)){
            $this->error('参数异常');
        }

        $userModel = new UserModel();
        $userInfo = $userModel->get($userId);

        $groupModel = new UserGroupModel();
        $groupList = $groupModel->order('createTime DESC')->select();

        $permissionService = new PermissionService();
        $menu = $permissionService->menu($user['userId']);

        $this->assign('menu', $menu);
        $this->assign('url', '/User/userList');
        $this->assign('userInfo', $userInfo);
        $this->assign('groupList', $groupList);
        $this->display();
    }

    /**
     * 保存权限
     */
    public function permissionSave()
    {
        $userId = I('post.id');
        $groupId = I('post.groupId');

        $userModel = new UserModel();
        $userEdit = $userModel->where('id = '.$userId)->setField('groupId', $groupId);
        if($userEdit){
            $this->success('分配成功', '/Admin/User/userList', 1);
        }else{
            $this->error('分配失败');
        }
    }
}